//
//  MYStatusListViewModel.swift
//  MYWeibo
//
//  Created by Magic Yu on 16/4/16.
//  Copyright © 2016年 Magic Yu. All rights reserved.
//

/*
负责加载网络数据 将网络数据处理成模型数组
给控制器的tableView提供模型数组
*/
import UIKit

class MYStatusListViewModel: NSObject {

    //模型数组
    lazy var statusArray: [MYStatusViewModel] = [MYStatusViewModel]()
    
    func loadHomePageData(isPullup: Bool,finishd:(isSuccess: Bool) -> ()) {
        
        guard let token = MYUserAccountViewModel.sharedAccountViewModel.userAccount?.access_token else {
            print("用户暂未登录")
            return
        }
        var max_id: Int64 = 0
        var since_id: Int64 = 0
        //不能同时指定max_id 和 since_id 这两个字段互斥 
        //根据标记判断需要哪个字段
        if isPullup {
            //上拉
            max_id = statusArray.last?.status?.id ?? 0
        }else {
            //下拉
            since_id = statusArray.first?.status?.id ?? 0
        }
        
        HMNetworkTools.sharedTools.loadHomePageData(token,max_id: max_id,since_id:since_id) { (result, error) -> () in
            
            if error != nil {
                //SVProgressHUD.showErrorWithStatus(AppError)
                finishd(isSuccess: false)
                return
            }
            
            //网络请求成功
            //print(result)
            
            //1.将result转换为字典
            guard let dict = result as? [String: AnyObject] else {
                //SVProgressHUD.showErrorWithStatus("数据格式错误")
                finishd(isSuccess: false)
                return
            }
            //2.根据statuses key 获取字典类型的数组
            guard let array = dict["statuses"] as? [[String: AnyObject]]  else {
                //SVProgressHUD.showErrorWithStatus("数据格式错误")
                finishd(isSuccess: false)
                return
            }
            //3.遍历数组
            //创建临时可变数组
            var tempArray = [MYStatusViewModel]()
            for item in array {
                //4.字典转模型
                let status = MYStatus(dict: item)
                let viewModel = MYStatusViewModel(status: status)
                //5.将模型添加到数组中
                tempArray.append(viewModel)
            }
            //保存数组
            //self.statusArray = tempArray
            //将新请求的旧 数据与之前的数据拼接到一起显示
            if isPullup {
                //上拉加载更多
                self.statusArray = self.statusArray + tempArray
            }else {
                //下拉刷新
                self.statusArray = tempArray + self.statusArray
            }
            //6.刷新tableView
            finishd(isSuccess: true)
        }
        
    }
    
}
